/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.race.service;

import com.lczyfz.istep.common.enums.JobIsFactoryType;
import com.lczyfz.istep.common.enums.JobStatus;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.service.CrudService;
import com.lczyfz.istep.modules.race.dao.RaceScheduleTeamSubjectDao;
import com.lczyfz.istep.modules.race.dao.RaceTeamScoreDao;
import com.lczyfz.istep.modules.race.entity.RaceSchedule;
import com.lczyfz.istep.modules.race.entity.RaceScheduleTeamSubject;
import com.lczyfz.istep.modules.race.entity.RaceTeamScore;
import com.lczyfz.istep.modules.race.web.RaceLoginController;
import com.lczyfz.istep.modules.sys.entity.ScheduleJob;
import com.lczyfz.istep.modules.sys.service.ScheduleJobService;
import com.lczyfz.istep.modules.sys.service.SystemService;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 团队历史分数Service
 * @author cfq
 * @version 2017-06-29
 */
@Service
@Transactional(readOnly = false)
//@Lazy(false)
public class RaceTeamScoreService extends CrudService<RaceTeamScoreDao, RaceTeamScore> {

	@Autowired
	ScheduleJobService scheduleJobService;

	@Autowired
	RaceScheduleService raceScheduleService;

	@Autowired
	RaceScheduleTeamSubjectDao raceScheduleTeamSubjectDao;

	@Autowired
	SystemService systemService;

	@Autowired
	RaceTeamScoreDao raceTeamScoreDao;

	public RaceTeamScore get(String id) {
		return super.get(id);
	}

	public List<RaceTeamScore> findList(RaceTeamScore raceTeamScore) {
		return super.findList(raceTeamScore);
	}

	public Page<RaceTeamScore> findPage(Page<RaceTeamScore> page, RaceTeamScore raceTeamScore) {
		return super.findPage(page, raceTeamScore);
	}

	@Transactional(readOnly = false)
	public void save(RaceTeamScore raceTeamScore) {
		super.save(raceTeamScore);
	}

	@Transactional(readOnly = false)
	public void delete(RaceTeamScore raceTeamScore) {
		super.delete(raceTeamScore);
	}

	/**
	 * 〈方法的功能描述〉:
	 * 定时任务-开始定时任务
	 *
	 * @param
	 * @return
	 * @Date 2016/12/6/11:20
	 * @author zy
	 * @methodName
	 **/
	@Transactional(readOnly = false)
	public void instanceScheduleJob(RaceSchedule raceScheduleInstance, String displaysize) throws Exception {

		logger.debug("instanceScheduleJob===定时任务开始");

		//加定时任务
		ScheduleJob scheduleJob = new ScheduleJob();
		scheduleJob.setJobName(raceScheduleInstance.getId());
		scheduleJob.setJobGroup("env_instance");
		scheduleJob.setBeanClass("com.lczyfz.istep.modules.race.service.RaceTeamScoreService");
		scheduleJob.setBeanName("raceTeamScoreService");
		scheduleJob.setMethodName("recordRaceScoreSchedule");

		String cronExpression = "0/5 * * * * ?";//每5秒
		if (Integer.parseInt(displaysize) >= 60) {
			cronExpression = "0 0 0/1 * * ?";//每一小时
		} else {
			cronExpression = "0 0/" + Integer.parseInt(displaysize) + " * * * ?";//根据设置的分钟数
		}
		logger.debug("真实任务定时表达式：" + cronExpression);

//		cronExpression = "0/5 * * * * ?";
		logger.debug("测试任务定时表达式：" + cronExpression);

		System.out.println("-----------刷新间隔" + cronExpression);

		scheduleJob.setCronExpression(cronExpression);



		scheduleJob.setIsConcurrent("1");
		scheduleJob.setStatus(JobStatus.Running.getValue());
		scheduleJob.setIsFactory(JobIsFactoryType.Factory.getValue());
		scheduleJobService.addTask(scheduleJob);


	}

	public void recordRaceScoreSchedule(ScheduleJob scheduleJob) throws Exception {
//		logger.debug("recordRaceScoreSchedule 定时任务执行");

		//获取开启赛程对象时间和当前时间
		RaceSchedule raceSchedule = raceScheduleService.scheduleStatus();
		Date endTime = raceSchedule.getEndTime();
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		dateFormat.format(now);

		//赛程时间结束或者关闭赛程，清除定时任务
		if (endTime.before(now) || raceSchedule.getScheduleStatus().equals("0")) {

			//倒计时结束，重置第一到第五名提交的计数器
			RaceLoginController.number = 0;

//			logger.debug("关闭定时任务执行");

			scheduleJob.setStatus(JobStatus.Stopped.getValue());
			scheduleJobService.save(scheduleJob);
			scheduleJobService.deleteJob(scheduleJob);
		} else {
//			logger.debug("启动定时任务执行");
			List<RaceScheduleTeamSubject> raceScheduleTeamSubjects = raceScheduleTeamSubjectDao.teamTotalScoreRanking();
//			logger.debug("数量" + raceScheduleTeamSubjects.size());
			if (raceScheduleTeamSubjects.size() > 0) {
				for (RaceScheduleTeamSubject raceScheduleTeamSubject : raceScheduleTeamSubjects) {
//					logger.debug("团队id" + raceScheduleTeamSubject.getTeamid());
//					logger.debug("团队分数" + raceScheduleTeamSubject.getScore());

					RaceTeamScore raceTeamScore = new RaceTeamScore();
					raceTeamScore.setScheduleId(raceScheduleTeamSubject.getScheduleid());
					raceTeamScore.setTeamName(raceScheduleTeamSubject.getTeamid());
					raceTeamScore.setTotalScore(raceScheduleTeamSubject.getScore());
					raceTeamScore.setCreateBy(systemService.getUser("1"));
					raceTeamScore.setUpdateBy(systemService.getUser("1"));
//					logger.debug("团队分数2" + raceTeamScore.toString());
					this.save(raceTeamScore);



				}
			}


		}

	}

	public void deleteScheduleJob(RaceSchedule raceSchedule) {
//		logger.debug("关闭定时任务执行");
		ScheduleJob scheduleJob = new ScheduleJob();
		scheduleJob.setJobName(raceSchedule.getId());
		scheduleJob.setJobGroup("env_instance");
		List<ScheduleJob> scheduleJobList = scheduleJobService.findList(scheduleJob);
		if (scheduleJobList.size() > 0) {
			for (ScheduleJob sj : scheduleJobList) {
				sj.setStatus(JobStatus.Stopped.getValue());
				scheduleJobService.save(sj);
				try {
					scheduleJobService.deleteJob(sj);
				} catch (SchedulerException e) {
					e.printStackTrace();
				}
			}
		}

	}


	public List<RaceTeamScore> findTeam(String teamName,String scheduleId) {
		return raceTeamScoreDao.findTeam(teamName,scheduleId);
	}
}